package com.lagou.service;

import com.lagou.dao.TokenDao;
import com.lagou.dao.UserDao;
import com.lagou.entity.Token;
import com.lagou.entity.User;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserService {

    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private UserDao userDao;

    public boolean isEmailRegistered(String email) {
        User user = new User();
        user.setEmail(email);
        return userDao.exists(Example.of(user));
    }

    public boolean checkPassword(String email, String password) {
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        return userDao.exists(Example.of(user));
    }

    public Token createToken(String email) {
        Token token = new Token();
        token.setEmail(email);
        token.setToken(RandomStringUtils.randomAlphanumeric(8));
        token.setCreateTime(new Date());
        tokenDao.saveAndFlush(token);
        return token;
    }

    public void createUser(String email, String password) {
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        user.setCreateTime(new Date());
        userDao.saveAndFlush(user);
    }

    public Token getToken(String tokenVal) {
        Token token = new Token();
        token.setToken(tokenVal);
        return tokenDao.findOne(Example.of(token)).orElse(null);
    }

}
